#pragma once
#include <memory>
#include "Connection.hpp"
#include "Channel.hpp"
#include "Socket.hpp"
#include "Common.hpp" //设置非阻塞
#include "Log.hpp"

using namespace LogModule;
using namespace SocketModule;

class Listener : public Connection
{
public:
    Listener(const InetAddr &addr)
        : _addr(addr)
    {
        _listensock = std::make_unique<TCPSocket>(addr, Type::SERVER);
        SetNonBlock(_listensock->Fd()); // 设置为非阻塞
        Connection::SetEvents(EPOLLIN | EPOLLET);
    }
    void Recver() override
    {
        LOG(LogLevel::DEBUG) << "ListenRecver Start, sockfd: " << _listensock->Fd();
        // ET模式，循环非阻塞读取
        while (true)
        {
            InetAddr addr;
            int sockfd = _listensock->Accept(&addr);
            if (sockfd < 0)
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK) // 非阻塞
                {
                    LOG(LogLevel::DEBUG) << "errno==EAGAIN";
                    break;
                }
                else if (errno == EINTR) // 被信号中断了
                {
                    LOG(LogLevel::DEBUG) << "errno==EINTR";
                    continue;
                }
                else
                {
                    Excepter(); // 统一异常处理
                    return;
                }
            }
            else
            {
                LOG(LogLevel::DEBUG) << "listener Recver success, client: "
                                     << addr.AddrString() << " sockfd: " << sockfd;
                // 1.创建普通套接字channel
                std::shared_ptr<Connection> conn = std::make_shared<Channel>(sockfd, addr);
                conn->SetEvents(EPOLLIN | EPOLLET);
                if (_handler != nullptr)
                    conn->RegisterHandler(_handler); // 普通套接字一人一份回调
                // 2.添加到_connections 和 内核中
                Connection::GetOwner()->AddConnection(conn);
            }
        }
        LOG(LogLevel::DEBUG) << "ListenRecver End";
    }
    void Sender() override
    {
    }
    void Excepter() override
    {
        Connection::GetOwner()->DelConnection(_listensock->Fd());
        LOG(LogLevel::INFO) << "except has been solved, sockfd: " << _listensock->Fd();
    }

    int GetFd() override
    {
        return _listensock->Fd();
    }

    ~Listener()
    {
    }

private:
    InetAddr _addr; // 服务器主机地址
    std::unique_ptr<Socket> _listensock;
};